<template>
  <div>
    <el-upload
      v-model:file-list="fileList"
      action="#"
      :accept="accept"
      :limit="limit"
      :list-type="listType"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
    >
      <template #trigger>
        <el-icon><Plus /></el-icon>
      </template>
      <template #tip>
        <div class="el-upload__tip text-red" v-if="tip">
          {{ tip }}
        </div>
      </template>
    </el-upload>
    <PreviewImg ref="previewImgRef" />
  </div>
</template>

<script setup>
  import { Plus } from "@element-plus/icons-vue";
  import { ElMessage, dayjs } from "element-plus";
  import PreviewImg from "/@/components/PreviewImg.vue";
  import { EstimatedTime } from "/@/utils/utils";

  const props = defineProps({
    // 文件格式
    accept: {
      type: String,
      default: ".jpeg,.png,.jpg", //* 全部
    },
    // 展示形式
    listType: {
      type: String,
      default: "picture-card",
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 限制
    limit: {
      type: Number,
      default: 1,
    },
    // 文件大小
    maxSize: {
      type: Number,
      default: 5, //MB
    },
    // 提示
    tip: {
      type: String,
      default: "",
    },
  });

  const fileList = ref([
    {
      name: "food.jpeg",
      url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
    },
  ]);
  const previewImgRef = ref();

  // 删除
  const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
  };

  // 图片预览
  const handlePictureCardPreview = (uploadFile) => {
    previewImgRef.value.open(uploadFile.url);
  };

  //上传文件之前的钩子
  const beforeUpload = (file) => {
    //限制上传文件大小
    const fileSize = file.size / 1024 / 1024;

    if (fileSize > props.maxSize) {
      ElMessage({
        message: `文件的最大大小为${props.maxSize}M`,
        type: "warning",
      });
      return false;
    }
  };
  // http请求
  const httpRequest = (options) => {
    const { onSuccess, onProgress, onError, file } = options;

    // 大文件分片上传
    const chunkSize = 1024 * 1024 * 1; // 分片大小
    const chunks = Math.ceil(file.size / chunkSize); // 分片数量
    ElMessage(`预计本次上传需要${EstimatedTime(chunks)}`);

    // const porps = {
    //   // 获取分片上传进度、断点和返回值。
    //   progress: (p, cpt, res) => {
    //     onProgress({ percent: p * 100 });
    //   },
    //   headers: {},
    //   parallel: chunks,
    //   partSize: chunkSize,
    //   meta: { year: dayjs().format("YYYY"), people: `${file.name}` },
    //   mime: "text/plain",
    // };

    //封装FormData对象
    const formData = new FormData();
    formData.append("file", file);

    console.log("formData", formData);
  };
</script>
